package com.stupidzhe.ds.linkedlist;

import java.util.Iterator;

/**
 * @Author: StupidZhe
 * @Date: Created in 2018/3/27
 * @Description: 只是一个单个元素只带next的简单链表
 */
public class SimpleLinkedList<T> implements Iterable<T> {

    // 首元素
    private Element<T> first;
    private int size;
    private Element<T> currentElement;

    public SimpleLinkedList() {
        first = new Element<T>(null, null);
        size = 0;
    }

    @Override
    public Iterator<T> iterator() {
        currentElement = first;
        return new Iterator<T>() {
            @Override
            public boolean hasNext() {
                return currentElement.next != null;
            }

            @Override
            public T next() {
                return (currentElement =
                        currentElement.next).val;
            }
        };
    }

    // list中单个元素
    private class Element<Any> {
        private Element<Any> next;
        private Any val;
        public Element(Element<Any> next, Any val) {
            this.next = next;
            this.val = val;
        }
    }

    public T add(T val) {
        Element<T> element = new Element<T>(null, val);
        Element<T> tmpElement = first;
        for (int n = 0; n < size; n++) {
            tmpElement = tmpElement.next;
        }
        tmpElement.next = element;
        size++;
        return val;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public T delete(T val) {
        Element<T> element = first;
        for (int n = 0; n < size; n++) {
            Element<T> tmpElement = element;
            element = element.next;
            if (element.val.equals(val)) {
                tmpElement.next = element.next;
                size--;
                return val;
            }
        }
        return null;
    }

    public T getFirst() {
        if (size == 0) {
            return null;
        }
        return first.next.val;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("SampleLinkedList{");
        Element<T> element = first;
        for (int n = 0; n < size; n++) {
            element = element.next;
            stringBuilder.append(element.val);
            stringBuilder.append(' ');
        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

    public int size() {
        return size;
    }


}
